//。订单流程详情页
//  NewOrderDetailViewController.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2018/3/7.
//  Copyright © 2018年 zjhcsoftios. All rights reserved.
//

#import "NewOrderDetailViewController.h"
#import "ZSBOrdorDetailSectionHeaderView.h"
#import "ZSBNewOrdorDetailCell.h"
#import "ZSBNewOrderButtomModel.h"
#import "ZSBNewOrdorDetailTitleModel.h"
#import "UITableViewCell+leoAdd.h"
#import "NSBundle+AssociatedBundle.h"
#import "UIColor+EX.h"
#import "NetworkAddress.h"
#import "SVProgressHUD.h"
#import "iSeeNetworkRequest.h"
#import <MJExtension/MJExtension.h>

@interface NewOrderDetailViewController ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, weak) IBOutlet UITableView *tableView;
//订单标题
@property (weak, nonatomic) IBOutlet UILabel *ordorTitleLabel;
//订单号
@property (weak, nonatomic) IBOutlet UILabel *ordorNumLabel;
//用户名
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
//手机号码
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
//左侧列表选择按钮
@property (weak, nonatomic) IBOutlet UIButton *leftOrdorButton;
//右侧列表选择按钮
@property (weak, nonatomic) IBOutlet UIButton *rightOrdorButton;
//滑块
@property (weak, nonatomic) IBOutlet UIView *slider;
//滑块距离左侧距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *silderLeftToSuperView;
//选择页面
@property (weak, nonatomic) IBOutlet UIView *chooseView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *chooseHeight;
//滑块距离位置控制
@property (nonatomic, assign) CGFloat sliderToLeftButton;
@property (nonatomic, assign) CGFloat sliderToRightButton;
//选中状态
@property (nonatomic, assign) NSInteger selectedIndex;
//底部取消订单以及充值页面
@property (weak, nonatomic) IBOutlet UIView *buttomView;
//取消订单按钮
@property (weak, nonatomic) IBOutlet UIButton *cannelOrdorButton;
//取消订单按钮控制
@property (nonatomic, assign) BOOL showCannelOrdorButton;
//订单充值按钮
@property (weak, nonatomic) IBOutlet UIButton *rechargeOrdorButton;
//取消充值按钮控制
@property (nonatomic, assign) BOOL showRechargeOrdorButton;
//低保取消页面高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomViewHeight;
//取消按钮右边距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cannelOrdorRightMargin;
//订单按钮右边距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rechageOrdorRightMargin;
//订单按钮宽度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cannelOrdorWidth;


//数据
//列表显示数据
@property (nonatomic, strong) NSMutableArray *dateList;
//预订单title列表
@property (nonatomic, strong) NSArray *titleList;

@property (nonatomic,strong) NSArray *statusListOne;

@property (nonatomic,strong) NSArray *statusListTwo;

@property (nonatomic, strong) NSArray *buttonList;

@end

@implementation NewOrderDetailViewController

static NSString *newOrdroDetailCellIdentify = @"newOrdroDetailCellIdentify";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.cannelOrdorButton.layer.cornerRadius = 3;
    self.cannelOrdorButton.layer.borderWidth = 1;
    self.cannelOrdorButton.layer.borderColor = [UIColor colorWithHexString:@"E21600"].CGColor;
    [self.cannelOrdorButton setTitleColor:[UIColor colorWithHexString:@"E21600"] forState:UIControlStateNormal];
    
    self.rechargeOrdorButton.layer.cornerRadius = 3;
    self.rechargeOrdorButton.layer.borderWidth = 1;
    self.rechargeOrdorButton.layer.borderColor = [UIColor colorWithHexString:@"169BD5"].CGColor;
    [self.rechargeOrdorButton setTitleColor:[UIColor colorWithHexString:@"169BD5"] forState:UIControlStateNormal];
    
    _dateList = [NSMutableArray array];
    
    _sliderToLeftButton = (kScreenWidth / 2 - 78) / 2;
    _sliderToRightButton = _sliderToLeftButton + kScreenWidth / 2;
    
    _leftOrdorButton.selected = YES;
    [self.view layoutIfNeeded];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZSBNewOrdorDetailCell" bundle:[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"]] forCellReuseIdentifier:newOrdroDetailCellIdentify];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"刷新"] style:UIBarButtonItemStylePlain target:self action:@selector(reloadButtonAction)];
    
    [self hiddenChooseView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self getList];
}

- (void)back
{
    NSArray *controllers = self.navigationController.childViewControllers;
    for (NSInteger i = controllers.count; i < 0; i--) {
        UIViewController *popViewController = controllers[i];
        if ([popViewController isKindOfClass:NSClassFromString(@"ZSBOrderListViewController")] || [popViewController isKindOfClass:NSClassFromString(@"ZPZPHCNewHomePageCtrl")]) {
            [self.navigationController popToViewController:popViewController animated:YES];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 按钮点击事件
- (IBAction)ordorButtonAction:(UIButton *)sender {
    
    if (sender.isSelected == YES) {
        return;
    }else {
        if (sender == _leftOrdorButton) {
            _leftOrdorButton.selected = YES;
            _rightOrdorButton.selected = NO;
            [UIView animateWithDuration:.35 animations:^{
                self.silderLeftToSuperView.constant = self.sliderToLeftButton;
                [self.view layoutIfNeeded];
            }];
            [_dateList removeAllObjects];
            [_dateList addObjectsFromArray:_statusListOne];
            [_tableView reloadData];
        }else {
            _leftOrdorButton.selected = NO;
            _rightOrdorButton.selected = YES;
            [UIView animateWithDuration:.35 animations:^{
                self.silderLeftToSuperView.constant = self.sliderToRightButton;
                [self.view layoutIfNeeded];
            }completion:^(BOOL finished) {
                [self.dateList removeAllObjects];
                [self.dateList addObjectsFromArray:self.statusListTwo];
                [self.tableView reloadData];
            }];
        }
        _selectedIndex = sender.tag - 200;
    }
    
}

- (IBAction)cannelOrdorButtonAction:(UIButton *)sender {
    
    UIAlertController *cannelAction = [UIAlertController alertControllerWithTitle:@"提示" message:@"你将取消该订单" preferredStyle:UIAlertControllerStyleAlert];
    [cannelAction addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [cannelAction addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self cannelOrdor];
    }]];
    [self presentViewController:cannelAction animated:YES completion:nil];
}

- (IBAction)rechargeOrdorButtonAction:(UIButton *)sender {
    
    [self rechargeOrdor];
}

- (void)reloadButtonAction {
    [self getList];
}

#pragma mark 数据重载


- (void)resetView {
    _userNameLabel.text = _statusInfo.name;
    _phoneLabel.text = _statusInfo.ywhm;
    if (_statusInfo.type == 1) {
        _ordorTitleLabel.text = @"商机订单号：";
        _ordorNumLabel.text = _statusInfo.sjKey;
    }else {
        _ordorTitleLabel.text = @"iSale单号：";
        _ordorNumLabel.text = _statusInfo.sgKey;
    }
    
    if (_titleList.count == 1) {
        if (_chooseView.hidden == NO) {
            [self hiddenButtomView];
        }
        [_dateList removeAllObjects];
        [_dateList addObjectsFromArray:_statusListOne];
        [_tableView reloadData];
    }else if (_titleList.count >= 2) {
        if (_chooseView.hidden == YES) {
            [self setTableTitles];
            [self showChooseView];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.51 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.dateList removeAllObjects];
            [self.dateList addObjectsFromArray:self.statusListOne];
            [self.tableView reloadData];
        });
    }
    
    [self reloadButtomView];
    
}

- (void)setTableTitles {
    for (int i = 0; i < _titleList.count; i++) {
        UIButton *button = [self.view viewWithTag:i + 200];
        ZSBNewOrdorDetailTitleModel *model = _titleList[i];
        [button setTitle:model.statusName forState:UIControlStateNormal];
        [button setTitle:model.statusName forState:UIControlStateSelected];
        if (i == 0) {
            _selectedIndex = 0;
            _leftOrdorButton.selected = YES;
        }
    }
}





#pragma mark 页面显示隐藏方法

- (void)showChooseView {
    [UIView animateWithDuration:.25 animations:^{
        self.chooseView.hidden = NO;
        self.chooseHeight.constant = 40;
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
        [UIView animateWithDuration:.25 animations:^{
            self.silderLeftToSuperView.constant = self.sliderToLeftButton;
            [self.view layoutIfNeeded];
        }];
    }];
}

- (void)hiddenChooseView {
    [UIView animateWithDuration:.25 animations:^{
        [UIView animateWithDuration:.25 animations:^{
            self.silderLeftToSuperView.constant = -78;
            [self.view layoutIfNeeded];
        }];
    }completion:^(BOOL finished) {
        self.chooseView.hidden = YES;
        self.chooseHeight.constant = 0;
        [self.view layoutIfNeeded];
    }];
}

- (void)showButtomView {
    [UIView animateWithDuration:.25 animations:^{
        self.buttomView.hidden = NO;
        self.buttomViewHeight.constant = 51;
        [self.view layoutIfNeeded];
    }];
    
    [self showCannelOrdorButtonOrChargeOrdorButton];
}

- (void)hiddenButtomView {
    [UIView animateWithDuration:.25 animations:^{
        self.buttomView.hidden = YES;
        self.buttomViewHeight.constant = 0;
        [self.view layoutIfNeeded];
    }];
}

- (void)reloadButtomView {
    if (_buttonList.count == 0) {
        if (_buttomView.hidden == NO) {
            [self hiddenButtomView];
        }
    }else {
        if (_buttomView.hidden == YES) {
            [self showButtomView];
            
        }
    }
}

- (void)showCannelOrdorButtonOrChargeOrdorButton {
    
    _showCannelOrdorButton = NO;
    _showRechargeOrdorButton = NO;
    for (int i = 0; i < _buttonList.count; i++) {
        ZSBNewOrderButtomModel *model = _buttonList[i];
        if ([model.buttonLabel isEqualToString:@"取消订单"]) {
            _showCannelOrdorButton = YES;
        }else if ([model.buttonLabel isEqualToString:@"支付订单"]) {
            _showRechargeOrdorButton = YES;
        }
    }
    
    if (_showCannelOrdorButton && _showRechargeOrdorButton) {
        [UIView animateWithDuration:.25 animations:^{
            self.cannelOrdorButton.hidden = NO;
            self.rechargeOrdorButton.hidden = NO;
            self.cannelOrdorWidth.constant = 75;
            self.rechageOrdorRightMargin.constant = 15;
            [self.view layoutIfNeeded];
        }];
    }else if (_showCannelOrdorButton) {
        [UIView animateWithDuration:.25 animations:^{
            self.cannelOrdorButton.hidden = NO;
            self.rechargeOrdorButton.hidden = YES;
        }];
    }else if (_showRechargeOrdorButton) {
        [UIView animateWithDuration:.25 animations:^{
            self.cannelOrdorButton.hidden = YES;
            self.cannelOrdorWidth.constant = 0;
            self.rechageOrdorRightMargin.constant = 0;
            self.rechargeOrdorButton.hidden = NO;
            [self.view layoutIfNeeded];
        }];
    }else {
        [UIView animateWithDuration:.25 animations:^{
            self.cannelOrdorButton.hidden = YES;
            self.rechargeOrdorButton.hidden = YES;
        }];
    }
    
    
}




#pragma mark 网络请求
- (void)getList
{
    [SVProgressHUD show];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    if (self.statusInfo && self.statusInfo.tradeOrderNum.length > 0) {
        [params setObject:self.statusInfo.tradeOrderNum forKey:@"tradeOrderNum"];
    }
    [params setObject:@"all" forKey:@"statusType"];
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPOrdorProcessDetail) params:params success:^(id object) {
        self.statusInfo = [ZSBStatusInfo mj_objectWithKeyValues:object[@"body"][@"result"][@"tradeInfo"]];
        self.buttonList = [ZSBNewOrderButtomModel mj_objectArrayWithKeyValuesArray:object[@"body"][@"result"][@"buttonList"]];
        self.titleList = [ZSBNewOrdorDetailTitleModel mj_objectArrayWithKeyValuesArray:object[@"body"][@"result"][@"titleList"]];
        self.statusListOne = [ZSBStatusDetailInfo mj_objectArrayWithKeyValuesArray:object[@"body"][@"result"][@"statusListOne"]];
        self.statusListTwo = [ZSBStatusDetailInfo mj_objectArrayWithKeyValuesArray:object[@"body"][@"result"][@"statusListTwo"]];
        
        [SVProgressHUD dismiss];
        
        [self resetView];
    } failure:^(NSError *error) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [dic objectForKey:@"msg"];
        [SVProgressHUD showErrorWithStatus:msg];
    }];

}

- (void)cannelOrdor {
    [SVProgressHUD showWithStatus:@"" ];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:_statusInfo.tradeOrderNum forKey:@"tradeOrderNum"];
    if (self.statusInfo.type == 0) {
        
        [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ISEE_URL_GET_CANCEL_SALEORDER) params:params success:^(id object) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ZSBOrderListViewControllerRefreshData" object:nil];
            [self back];
            
            
            [SVProgressHUD dismiss];
            
            [SVProgressHUD showSuccessWithStatus:object[@"msg"]];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络不好，请稍后再试"];
        }];
        
    }else{
        
        [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ISEE_URL_GET_CANCEL_SJORDER) params:params success:^(id object) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ZSBOrderListViewControllerRefreshData" object:nil];
            [SVProgressHUD dismiss];
            
            [SVProgressHUD showSuccessWithStatus:object[@"msg"]];
            
            [self back];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络不好，请稍后再试"];
        }];
        
    }
}

- (void)rechargeOrdor {
    [SVProgressHUD showWithStatus:@"" ];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:_statusInfo.tradeOrderNum forKey:@"tradeOrderNum"];
    if (self.statusInfo.type == 0) {
        [params setObject:@"sl" forKey:@"payType"];
    }else{
        [params setObject:@"sj" forKey:@"payType"];
    }
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ISEE_URL_GET_ASSEMBLECHARGURLFORMYBILL) params:params success:^(id object) {
        NSDictionary *body = object[@"body"];
        
        
        if ([self isEmptyString:body[@"payUrlForBill"]].length > 0) {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:body[@"payUrlForBill"]]];
        }
        
        
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络不好，请稍后再试"];
    }];
    
}



#pragma mark tableDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    ZSBOrdorDetailSectionHeaderView *sectionHeadView = [[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"] loadNibNamed:@"ZSBOrdorDetailSectionHeaderView" owner:self options:nil].lastObject;
    if (self.statusInfo.type == 0) {
        sectionHeadView.tableTitle.text = @"快捷受理流程状态";
    }else{
        sectionHeadView.tableTitle.text = @"商机处理流程状态";
    }
    return sectionHeadView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .01;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_dateList.count > 0) {
        return 1;
    }else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dateList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZSBNewOrdorDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:newOrdroDetailCellIdentify forIndexPath:indexPath];
    cell.model = _dateList[indexPath.row];
    if (indexPath.row == 0) {
        cell.isFirstCell = YES;
        if (_dateList.count == 1) {
            cell.isLastCell = YES;
        }
    }else if (indexPath.row == _dateList.count - 1) {
        cell.isLastCell = YES;
    }else {
        cell.isMiddleCell = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // animationStyle: 动画类型
    [cell tableView:tableView forRowAtIndexPath:indexPath animationStyle:UITableViewCellDisplayAnimationRight];
}


- (NSString *)isEmptyString:(id)object
{
    if ((NSNull *)object == [NSNull null]) {
        return @"";
    }
    if (object) {
        return [NSString stringWithFormat:@"%@",object];
    }else{
        return @"";
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



@end
